import { defineStore } from "pinia";
import { UserState } from "@/stores/interface";
import { CANROCNET } from "@/api/config/servicePort";
import piniaPersistConfig from "@/stores/helper/persist";

export const useUserStore = defineStore({
  id: "canroc-user",
  state: (): UserState => ({
    token: "",
    refreshToken: "",
    expiredTime: 0,
    userInfo: undefined
  }),
  getters: {
    /**
     * 是否登录
     */
    isLogin(): boolean {
      return !!this.token;
    },
    /**
     * 是否过期
     */
    isExpired(): boolean {
      const now = new Date();
      const differenceInMilliseconds = this.expiredTime - Math.round(now.getTime() / 1000);
      return differenceInMilliseconds < 10;
    }
  },
  actions: {
    // Set Token
    setToken(token: string, refreshToken: string) {
      this.token = token;
      this.refreshToken = refreshToken;
      if (!token) {
        this.expiredTime = 0;
        this.userInfo = undefined;
        return;
      }

      // 获取token过期时间
      const tokenParts = token.split(".");
      // 处理URL安全编码（如果适用）
      const urlSafePayload = tokenParts[1].replace(/-/g, "+").replace(/_/g, "/");
      // 使用atob函数进行base64解码
      const decodedPayload = atob(urlSafePayload);
      // 去除可能存在的填充字符（如果有的话）
      const trimmedPayload = decodedPayload.replace(/=+$/, "");
      // 将解码后的字符串转换为JSON对象
      const payload = JSON.parse(trimmedPayload);
      this.expiredTime = payload.exp;
    },
    // Set setUserInfo
    setUserInfo(userInfo: UserState["userInfo"]) {
      // 判断头像是否为/avatar/开头
      if (userInfo?.avatar && userInfo.avatar.startsWith("/avatar/")) {
        userInfo.avatar = CANROCNET + userInfo.avatar;
      }

      this.userInfo = userInfo;
    }
  },
  persist: piniaPersistConfig("canroc-user")
});
